package com.oazon.common.util;

import java.io.StringBufferInputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONException;
import org.json.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@SuppressWarnings("deprecation")
public class XmlUtil {

	/**
	 * 获得xml的body部分，再转成json
	 * 
	 * @param xml
	 * @return
	 */
	public static String cXml2Json(String xml) {
		return xml2Json(XmlNode2String(getXmlBody(xml)));
	}

	/**
	 * 将xml格式转为json格式
	 * 
	 * @param xml
	 * @return
	 */
	public static String xml2Json(String xml) {
		if (xml == null) {
			return null;
		}
		String json = null;
		try {
			json = XML.toJSONObject(xml).toString();

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json;
	}

	public static String XmlNode2String(Node node) {
		if (node == null) {
			return null;
		}
		Transformer transformer = null;
		try {
			transformer = SAXTransformerFactory.newInstance().newTransformer();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		}
		if (transformer != null) {
			try {
				StringWriter sw = new StringWriter();
				transformer
						.transform(new DOMSource(node), new StreamResult(sw));
				return sw.toString();
			} catch (Exception te) {
				throw new RuntimeException(te.getMessage());
			}
		}
		return "";
	}

	public static Node getXmlBody(String xml) {
		if (xml == null) {
			return null;
		}
		Node response = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			// 生成DocumentBuilder
			DocumentBuilder builder = factory.newDocumentBuilder();
			// 调用完这句后XML文档解析完成，暂存在内存中
			Document document = builder.parse(new StringBufferInputStream(xml));

			// 获得根元素
			Element root = document.getDocumentElement();
			NamedNodeMap res = root.getAttributes();
			String xmlns = "";
			for (int i = 0; i < res.getLength(); i++) {
				Node node = res.item(i);
				String name = node.getNodeName();
				String value = node.getNodeValue();
				if (value
						.equalsIgnoreCase("http://schemas.xmlsoap.org/soap/envelope/")) {
					xmlns = name.substring("xmlns:".length()) + ":";
				}
			}
			// 匹配结点，返回结点集
			NodeList personNodes = root.getElementsByTagName(xmlns + "Body");
			Node body = personNodes.item(0);
			response = body.getFirstChild();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
}